2- Create Interactive Web Graphics via ‘plotly’

Reference: https://plot.ly/r

US economic time series

library(plotly)
data("economics")
head(economics)
## # A tibble: 6 x 6
##   date         pce    pop psavert uempmed unemploy
##   <date>     <dbl>  <int>   <dbl>   <dbl>    <int>
## 1 1967-07-01  507. 198712    12.5     4.5     2944
## 2 1967-08-01  510. 198911    12.5     4.7     2945
## 3 1967-09-01  516. 199113    11.7     4.6     2958
## 4 1967-10-01  513. 199311    12.5     4.9     3143
## 5 1967-11-01  518. 199498    12.5     4.7     3066
## 6 1967-12-01  526. 199657    12.1     4.8     3018
attach(economics)

Description

This dataset was produced from US economic time series data available from http://research.stlouisfed.org/fred2. economics is in “wide” format, economics_long is in “long” format.

Line (Time series) plots

plot_ly (
  x = date,
  y = unemploy,
  type = 'scatter',
  mode = 'lines' )

Scatter plots

p <- plot_ly (
      x = pce,
      y = unemploy,
      type = 'scatter',
      mode = 'markers')
p
add_paths(p)
plot_ly(x = date, y = uempmed, color = I("red"), 
        showlegend = FALSE) %>% add_lines() %>% add_markers(color=pop)
plot_ly(x = date,y = uempmed) %>% add_ribbons(ymin = pce - 1e3, ymax = pce + 1e3)

Use group_by() to apply visual mapping once per group (e.g. one line per group)

data(txhousing)
head(txhousing)
## # A tibble: 6 x 9
##   city     year month sales   volume median listings inventory  date
##   <chr>   <int> <int> <dbl>    <dbl>  <dbl>    <dbl>     <dbl> <dbl>
## 1 Abilene  2000     1    72  5380000  71400      701       6.3 2000 
## 2 Abilene  2000     2    98  6505000  58700      746       6.6 2000.
## 3 Abilene  2000     3   130  9285000  58100      784       6.8 2000.
## 4 Abilene  2000     4    98  9730000  68600      785       6.9 2000.
## 5 Abilene  2000     5   141 10590000  67300      794       6.8 2000.
## 6 Abilene  2000     6   156 13910000  66900      780       6.6 2000.
txhousing %>%
group_by(txhousing$city) %>%
plot_ly(x = txhousing$date, y = txhousing$median) %>%
add_lines(color = txhousing$city)
x <- c(1, 2, 2, 1, 1, 2)
y <- c(1, 2, 2, 1, 1, 2)
z <- c(1, 1, 2, 2, 3, 3)
df <- data.frame(x = x,y = y,z = z)
plot_ly(df) %>% add_markers(x = 1.5, y = 1.5) %>% add_markers(x = x, y = y,frame = z)
p <- plot_ly(economics[1:20,]) %>% add_markers(x = ~pop,y = ~unemploy,size = ~psavert,color=~uempmed)
colorbar(p, len = 0.5)

Boxplots Plots in plotly

plot_ly(midwest, x = ~percollege, color = ~state, type = "box")

3D Plots in plotly

plot_ly(z = ~volcano) %>% add_surface()